package com.spider.websocket;

import com.spider.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * socket服务端
 *
 * @author panglin
 * @date 2020/11/23 20:17
 */
@Component
@ServerEndpoint("/task/update/{name}")
public class WebSocketServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 实现在线人数计数
     */
    private static int onLineCount = 0;

    /**
     * 存储每一个会话对象
     */
    private static final ConcurrentHashMap<String, WebSocketServer> WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP = new ConcurrentHashMap<>();

    private Session session;

    private String userName;

    /**
     * 建立连接
     *
     * @param session
     * @param userName
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("name") String userName) {
        this.session = session;
        this.userName = userName;
        if (WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.containsKey(userName)) {
            WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.remove(userName);
            WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.put(userName, this);
        } else {
            WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.put(userName, this);
            addOnlineCount();
        }
        LOGGER.info("当前连接人数为{}", getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.info("用户{}连接失败", this.userName);
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.containsKey(userName)) {
            WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.remove(userName);
            //从set中删除
            subOnlineCount();
        }
        LOGGER.info("用户退出:" + userName + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 错误处理
     *
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        LOGGER.info("用户错误{}", this.userName);
        throwable.printStackTrace();
    }

    /**
     * 发送消息
     *
     * @param userName
     * @param message
     */
    public static void sendInfo(@PathParam("name") String userName, String message) {
        if (StringUtils.isNotEmpty(userName) && WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.containsKey(userName)) {
            try {
                WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.get(userName).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            LOGGER.info("当前用户不在线{}", userName);
        }
    }

    /**
     * 群发消息
     *
     * @param message
     */
    public static void sendMessageByGroup(String message) {
        WEB_SOCKET_SERVER_CONCURRENT_HASH_MAP.forEachKey(2, (k) -> sendInfo(k, message));
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized void addOnlineCount() {
        onLineCount++;
    }

    public static synchronized void subOnlineCount() {
        onLineCount--;
    }

    public static synchronized Integer getOnlineCount() {
        return onLineCount;
    }
}
